import React, { useCallback, useEffect, useState } from 'react';
import NavBar from '@/components/NavBar/NavBar';
import { Link, useNavigate } from 'react-router-dom';
import { Button, ImageUploader, ImageUploadItem, NoticeBar, TextArea, Toast } from 'antd-mobile';
import Radio from '@/components/Radio/Radio';
import { allergicHistoryOptions, fertilityStatusOptions, liverFunctionOptions, renalFunctionOptions } from '@/constants/constult';
import { ConsultMedicine as Medicine } from '@/type/ConsultType';
import { UploadResponse } from '@/API/commonAPI';
import { setConsultMedicineInfo, upload } from '@/store/modules/consultStore';
import { useEnhanceDispatch } from '@/hooks';
import Upload from '@/components/Upload/Upload';
import './ConsultMedicine.scss';


const ConsultMedicine = () => {
  const demoLongText = '请如实填写资料以便医生了解您的病情和用药需求';

  const enhanceDispatch = useEnhanceDispatch();
  const navigate = useNavigate();
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>开药门诊</span>), []);
  // 右边插槽内容
  const right = useCallback(() => (<Link to="/">问诊记录</Link>), []);
  // 图片列表
  const [fileList, setFileList] = useState<ImageUploadItem[]>([]);
  // 开药问诊的表单数据
  const [consultMedicine, setConsultMedicine] = useState<Medicine>({
    illnessDesc: '',
    liverFunction: 0,
    renalFunction: 0,
    allergicHistory: 0,
    fertilityStatus: 0,
    pictures: [],
  });

  /**
   * @description上传的回调函数，入参是需要被上传的文件对象，经过异步处理之后，返回上传结果
   * */
  const onUpload = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    const uploadResponse: UploadResponse = await enhanceDispatch(upload(formData)).unwrap();
    return uploadResponse;
  };

  /**
   *@description 已上传的文件列表变化时触发的回调函数
   * */
  const onChangeFieList = (uploads: ImageUploadItem[]) => {
    setFileList(uploads);
  };

  /**
   *@description 文件读取前的回调函数，返回null可终止文件读取，支持返回 Promise
   * */
  const beforeUpload = (file: File) => {
    if (file.size > 1024 * 1024) {
      Toast.show('请选择小于 1M 的图片');
      return null;
    }
    return file;
  };

  /**
   *@description 点击下一步按钮的回调函数 记录病情描述并且跳转到患者列表页面
   * */
  const handleNext = () => {
    enhanceDispatch(setConsultMedicineInfo(consultMedicine));
    navigate(`/patient?selected=Medicine`);
  };

  /**
   *监听fileList数组的变化，收集参数准备带给服务器
   * */
  useEffect(() => {
    setConsultMedicine({ ...consultMedicine, pictures: fileList as { id: string, url: string }[] });
  }, [fileList]);

  return (
    <div className="consult-medicine">
      {/*导航栏组件*/}
      <NavBar back={left()} children={children()} right={right()} onBack={() => navigate(-1)}></NavBar>
      <NoticeBar content={demoLongText} color="alert" />
      {/*收集信息*/}
      <div className="illness-form">
        <div className="item">
          <p>患者症状描述</p>
          <TextArea style={{ '--font-size': '14px' }} showCount placeholder="请详细描述您的病情，病情描述不能为空" rows={3} onChange={(illnessDesc) => {
            setConsultMedicine({ ...consultMedicine, illnessDesc });
          }} />
        </div>
        <div className="item">
          <p>肝功能</p>
          <Radio optionsList={liverFunctionOptions} value={consultMedicine.renalFunction} onChange={(renalFunction) => {
            setConsultMedicine({ ...consultMedicine, renalFunction });
          }}></Radio>
        </div>
        <div className="item">
          <p>肾功能</p><Radio optionsList={renalFunctionOptions} value={consultMedicine.liverFunction} onChange={(liverFunction) => {
          setConsultMedicine({ ...consultMedicine, liverFunction });
        }}></Radio>
        </div>
        <div className="item">
          <p>过敏史</p>
          <Radio optionsList={allergicHistoryOptions} value={consultMedicine.allergicHistory} onChange={(allergicHistory) => {
            setConsultMedicine({ ...consultMedicine, allergicHistory });
          }}></Radio>
        </div>
        <div className="item">
          <p>生育状态及计划</p>
          <Radio optionsList={fertilityStatusOptions} value={consultMedicine.fertilityStatus} onChange={(fertilityStatus) => {
            setConsultMedicine({ ...consultMedicine, fertilityStatus });
          }}></Radio>
        </div>
        <div className="item">
          <p>上传病例信息</p>
          <ImageUploader maxCount={3} value={fileList} onChange={onChangeFieList} upload={onUpload} beforeUpload={beforeUpload}></ImageUploader>
        </div>
        <div className="item">
          <p>上传病例信息</p>
          <Upload fileList={fileList} setFileList={(uploads) => setFileList(uploads)}></Upload>
        </div>
        <Button color="primary" onClick={handleNext}>下一步</Button>
      </div>
    </div>
  );
};

export default ConsultMedicine;